package com.al.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.al.model.User;
import com.al.service.LoginService;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置字符编码
		req.setCharacterEncoding("UTF-8");
		//接受数据
		String name = req.getParameter("username");
		String password = req.getParameter("password");
		LoginService ls = new LoginService();
		User user = new User();
		try {
			user = ls.login(name,password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if(user.getName() == null || user.getName().equals("null") || user.getName().equals("")) {
			//登录失败
			resp.sendRedirect("login.jsp");
		}else {
			//密码正确
			req.setAttribute("username", user.getName());
			//请求转发
			req.getRequestDispatcher("index.jsp").forward(req, resp);
		}
	}
}
